package com.avic.rong.userOrder.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.userOrder.event.InformUpdate;
import com.avic.rong.userOrder.adapter.EditAddressAdapter;
import com.avic.rong.userOrder.api.AddressListApi;
import com.avic.rong.userOrder.bean.AddressListBean;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;

public class AddressListActivity extends BaseActivity {

    @BindView(R.id.edit_address_list)
    RecyclerView editAddressList;
    @BindView(R.id.iv_no_address)
    ImageView iv_no_address;
    @BindView(R.id.tv_add_address)
    TextView tvAddAddress;
    @BindView(R.id.loading_layout)
    LoadingLayout loading_layout;
    @BindView(R.id.ll_no_address)
    LinearLayout ll_no_address;
    private ArrayList<AddressListBean> listData = new ArrayList<>();
    private EditAddressAdapter editAddressAdapter;
    private int addressID;
    private String intentType;
    private String enterType;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_edit_address;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);

        addressID = getIntent().getIntExtra("addressID", -1);
        intentType = getIntent().getStringExtra("intentType");
        enterType = getIntent().getStringExtra("enterType");

        tvTitle.setText("收货地址");
        ll_no_address.setVisibility(View.GONE);

        editAddressList.setLayoutManager(new LinearLayoutManager(this));
        editAddressAdapter = new EditAddressAdapter(this, listData, addressID, intentType);
        editAddressList.setAdapter(editAddressAdapter);
        editAddressAdapter.setEnterType(enterType);
        initData();
    }

    public ArrayList checkAddress(ArrayList<AddressListBean> list, int addressId) {
        if (null != list && list.size() > 0) {
            AddressListBean ar = list.get(0);
            AddressListBean address = null;
            int index = 0;
            for (int i = 0, len = list.size(); i < len; i++) {
                if (list.get(i).getAddressId() == addressId) {
                    address = list.get(i);
                    index = i;
                }
            }
            if (list != null) {
                if (ar.getAddressId() != addressId && list.size() >= 2 && addressId != -1) {
                    if (ar.getIsDefault() == 1) {
                        list.remove(index);
                        list.add(1, address);
                        editAddressAdapter.address_postion = 1;
                    } else {
                        list.remove(index);
                        list.add(0, address);
                        editAddressAdapter.address_postion = 0;
                    }
                }
            }

        }
        return list;
    }

    public void initData() {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> map = new HashMap<>();
            map.put("token", getSharedPreferencesUtil().getLogintoken());
            final AddressListApi addressListApi = new AddressListApi(this, simpleOnNextListener);
            addressListApi.setCache(false);
            addressListApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(addressListApi);

            loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
                @Override
                public void onReload(View v) {
                    HttpManager.getInstance().doHttpDeal(addressListApi);
                    loading_layout.setStatus(LoadingLayout.LOADING);
                }

                @Override
                public void onReturn(View v) {
                    onBackPressed();
                }
            });
            loading_layout.setStatus(LoadingLayout.LOADING);
        } else {
            loading_layout.setStatus(LoadingLayout.EMPTY);
        }
    }

    //权威评测
    HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            listData.clear();
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(AddressListActivity.this, subjects.getMsg());
                return;
            }
            loading_layout.setStatus(LoadingLayout.SUCCESS);
            ArrayList<AddressListBean> data = (ArrayList<AddressListBean>) subjects.getData();
            ArrayList arrayList = checkAddress(data, addressID);
            listData.addAll(arrayList);
            if (listData.size() == 0 || listData == null) {
                ll_no_address.setVisibility(View.VISIBLE);
            } else {
                ll_no_address.setVisibility(View.GONE);
            }
            editAddressAdapter.notifyDataSetChanged();
        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };

    @Override
    protected void addListener() {
        editAddressAdapter.setOnClickItem(new EditAddressAdapter.OnClickItem() {
            @Override
            public void OnClickListion(View view, int postion) {

            }
        });
        tvAddAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //1  添加地址   2   编辑地址
                Intent intent = new Intent(AddressListActivity.this, UpdateAddressActivity.class);
                //用户无收货地址时新增收货地址“设置为默认地址”应默认勾选
                intent.putExtra("isAddressList", listData.size());

                intent.putExtra("address", 1);
                //地址跳转标记
                if (!TextUtils.isEmpty(intentType)) {
                    intent.putExtra("intentType", intentType);
                }


                startActivity(intent);
            }
        });
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listData != null && listData.size() > 0 && editAddressAdapter.getAddress_postion() != -3) {
                    InformUpdate informUpdate = new InformUpdate();
                    informUpdate.setEventType(informUpdate.MORE_ASSRESS_INFORM);
                    EventBus.getDefault().post(informUpdate);

                } else if (editAddressAdapter.getBackSelect() != -5 || editAddressAdapter.getAddress_postion() != -3) {
                    InformUpdate informUpdate = new InformUpdate();
                    informUpdate.setEventType(informUpdate.MORE_ASSRESS_INFORM);
                    EventBus.getDefault().post(informUpdate);
                } else if (editAddressAdapter.getBackSelect() == -5 && editAddressAdapter.getAddress_postion() == -3) {
                    InformUpdate informUpdate = new InformUpdate();
                    informUpdate.setEventType(informUpdate.NO_ASSRESS_INFORM);
                    EventBus.getDefault().post(informUpdate);
                }
                finish();
            }
        });

    }

    @Subscribe
    public void onEventShowThread(InformUpdate event) {
        if (event != null) {
            if (event.getEventType() == InformUpdate.ADD_ADDRESS_INFORM) {
                initData();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public static Intent queryIntent(Context context) {
        Intent intent = new Intent(context, AddressListActivity.class);
        return intent;
    }

}
